<?php

namespace App\Http\Controllers\API;

use Illuminate\Http\Request;
use Illuminate\Validation\Rule;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\DB;
use App\Http\Controllers\Controller;

class PluginListController extends Controller
{

    public function infos(Request $request)
    {
        $user = $request->user();
        $infos = \App\Models\Plugins\L1st::with(['items'])
            ->where('user_id', $user->id)
            ->where('category',$request->category)
            ->orderBy('priority', 'desc')
            ->get();

        return response()->json($infos, 200);
    }

    public function create(Request $request)
    {
        $rules = [
            'category' => ['required', Rule::in(['work','relax','explore'])],
            'ltype' => ['required', Rule::in(['daily', 'weekly', 'monthly', 'yearly', 'no-repeat'])],
            'display_name' => 'required|string|max:50',
            //'items' => 'required|array',
        ];

        $this->validate($request, $rules);

        return DB::transaction(function() use ($request) {
            //
            $user = $request->user();
            $items = (array)$request->items;
            $size = count($items);

            $info = new \App\Models\Plugins\L1st();
            $info->category = $request->category;
            $info->ltype = $request->ltype;
            $info->user_id = $user->id;
            $info->display_name = $request->display_name;
            $info->total_num = $size;
            $info->save();


            $priority = 100 * $size;
            foreach ($items as $v) {
                $item = new \App\Models\Plugins\L1stItem();
                $item->pid = $info->id;
                $item->content = $v['content'];
                $item->priority = $priority;
                $item->completed = array_get($v, 'completed') ? 1 : 0;
                $item->completed_at = $item->completed ? date('Y-m-d H:i:s') : null;
                $item->save();

                $priority = $priority - 100;
                $info->items[] = $item;
            }
            return response()->json($info, 201);
        });

    }

    public function update(Request $request, \App\Models\Plugins\L1st $list) {

        $list = $this->_update($request, $list);

        return response()->json($list, 201);
    }
    protected function _update(Request $request, \App\Models\Plugins\L1st $list) {

        return DB::transaction(function() use ($list, $request) {
            //
            $items = (array)$request->items;
            $size = count($items);

            $priority = 100 * $size;
            $ids = $nitems = [];
            $completed_num = 0;
            foreach ($items as $v) {
                $itemid = (int)array_get($v, 'id');
                $item = \App\Models\Plugins\L1stItem::firstOrCreate(['id'=>$itemid, 'pid'=>$list->id], []);
                $item->content = $v['content'];
                $item->priority = $priority;

                if(!$item->completed && array_get($v, 'completed'))  {
                    $item->completed = 1;
                    $item->completed_at = date('Y-m-d H:i:s');
                } else if($item->completed && array_get($v, 'completed') == 0) {
                    $item->completed = 0;
                    $item->completed_at = null;
                }

                $item->save();

                $ids[] = $item->id;
                $nitems[] = $item;
                $priority = $priority - 100;
                if($item->completed_at) $completed_num++;
            }


            $list->ltype = $request->ltype;
            $list->display_name = $request->display_name;
            $list->total_num = $size;
            $list->completed_num = $completed_num;
            $list->save();

            \App\Models\Plugins\L1stItem::where('pid', $list->id)
                ->whereNotIn('id',$ids)->delete();

            $list->items = $nitems;
            return $list;
        });
    }

    public function updateAll(Request $request) {
        $lists = (array)$request->lists;
        $_lists = [];
        DB::beginTransaction();
        foreach ($lists as $k=>$v) {

            if($v['id'] == 0)   continue;

            $list = \App\Models\Plugins\L1st::find($v['id']);

            if(!$list)   continue ;

            $proxy = new Request();
            $proxy->merge($v);
            $_lists[] = $this->_update($proxy, $list);
        }
        DB::commit();
        return response()->json($_lists, 201);
    }

    public function delete(Request $request, \App\Models\Plugins\L1st $list)
    {

        $user = $request->user();

        if($list->user_id != $user->id) return response()->json('no permission', 401);

        if(!$list) return response()->json('resource not found', 404);

        DB::transaction(function() use ($request, $list) {
            \App\Models\Plugins\L1stItem::where('pid', $list->id)->delete();
            $list->delete();
        });

        return response()->make('', 204);
    }

}
